package com.com.gmail.at.vssabinin.client;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import DTO.PassengerDTO;
import DTO.ScheduleDTO;
import DTO.TicketDTO;
import javax.swing.JButton;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;


public class Main extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;

	public Main() {
		setResizable(false);
        initComponents();
    }
    
    public InetAddress adress;
    
    public Client client;

    public static Main mainInstance = new Main();
    
    public PassengerDTO passenger = null;
    
    public void loginViewSet() {
    	mainInstance.setLocationRelativeTo(null);
    	mainInstance.setVisible(true);
    	Main.mainInstance.client.sendThroughProtocol("clientRefreshSelfInfo", passenger);
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	this.passenger = (PassengerDTO) message.getObject();
        	mainInstance.jLabel2.setText("Hello, " + passenger.getPassengerName() + "  " 
        			 + passenger.getPassengerSurname());
            DefaultListModel listModel = new DefaultListModel();
            if (passenger.getTickets() != null) {
            	listModel.clear();
            for (TicketDTO ticket : passenger.getTickets()) {
            	listModel.addElement("Ticket number:   "  + ticket.getTicketID()  + "   ticket price:   " 
                 			+ ticket.getPrice().toString());
            }
            }
            mainInstance.ticketsList.setModel(listModel);
        } else if (message.getType().equals("no")) {
        	JOptionPane.showMessageDialog(null, "Sorry, some internal error!!!");
        }	
    }
   
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        viewTicket = new javax.swing.JButton();
        sellTickets = new javax.swing.JButton();
        logOut = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        
        this.addWindowListener( 
        	new WindowAdapter() { 
        		public void windowClosing(WindowEvent e) { 
        			exit(); 
        	    } 
        	} 
        );

        jLabel1.setText("Your tickets:");

        jLabel2.setText("Your name and surname:");

        viewTicket.setText("View ticket information");

        sellTickets.setText("Sell selected ticket");

        logOut.setText("Log out");
        logOut.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                logOutMouseReleased(evt);
            }
        });
        
        sellTickets.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                sellTicketsMouseReleased(evt);
            }
        });

        viewTicket.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                viewTicketMouseReleased(evt);
            }
        });
        
        JButton viewSchedule = new JButton("View station's schedule");
        
        viewSchedule.addMouseListener(new java.awt.event.MouseAdapter() {
        	public void mouseReleased(java.awt.event.MouseEvent evt) {
        		viewScheduleMouseReleased(evt);
            }         
        });
        
        searchTrains = new JButton("Search trains and buy tickets");
        
        searchTrains.addMouseListener(new java.awt.event.MouseAdapter() {
        	public void mouseReleased(java.awt.event.MouseEvent evt) {
        		searchTrainsMouseReleased(evt);
            }         
        });
       
        ticketsList = new javax.swing.JList();
        ticketsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                ticketsList.setModel(new javax.swing.AbstractListModel() {
                    /**
					 * 
					 */
					private static final long serialVersionUID = 1L;
					String[] strings = { "Tickets" };
                    public int getSize() { return strings.length; }
                    public Object getElementAt(int i) { return strings[i]; }
                });
        
        JButton refresh = new JButton("Refresh tickets");
        
        refresh.addMouseListener(new java.awt.event.MouseAdapter() {
        	public void mouseReleased(java.awt.event.MouseEvent evt) {
        		refreshMouseReleased(evt);
            }         
        });
         

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addComponent(ticketsList, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        				.addComponent(jScrollPane1, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
        					.addComponent(jLabel2)
        					.addPreferredGap(ComponentPlacement.RELATED, 207, Short.MAX_VALUE)
        					.addComponent(logOut))
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(refresh)
        					.addGap(247)
        					.addComponent(jLabel1))
        				.addGroup(layout.createSequentialGroup()
        					.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
        						.addComponent(sellTickets, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        						.addComponent(viewTicket, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        					.addGap(84)
        					.addGroup(layout.createParallelGroup(Alignment.TRAILING)
        						.addComponent(viewSchedule, GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
        						.addComponent(searchTrains, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))))
        			.addContainerGap())
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(logOut)
        				.addComponent(jLabel2))
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(23)
        					.addComponent(jLabel1))
        				.addGroup(layout.createSequentialGroup()
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(refresh)))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(ticketsList, GroupLayout.PREFERRED_SIZE, 183, GroupLayout.PREFERRED_SIZE)
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        			.addGap(11)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(viewSchedule)
        				.addComponent(viewTicket))
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(searchTrains)
        				.addComponent(sellTickets))
        			.addContainerGap())
        );
        getContentPane().setLayout(layout);
        
        pack();
    }
    
    public void exit() {
    	this.client.stopClient();
    	this.dispose();
    }

    private void logOutMouseReleased(java.awt.event.MouseEvent evt) {
        Main.mainInstance.client.sendThroughProtocol("logout", passenger);
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	Main.mainInstance.passenger = null;
            mainInstance.setVisible(false);
            Login.loginInstance.setVisible(true);
        }  else if (message.getType().equals("no")) {
        	JOptionPane.showMessageDialog(null, "Sorry, some internal error!!!");
        }	
    }
    
    private void viewScheduleMouseReleased(java.awt.event.MouseEvent evt) {
		mainInstance.setVisible(false);
		StationSchedule.stationScheduleInstance.setLocationRelativeTo(null);
        StationSchedule.stationScheduleInstance.setVisible(true);
	}
    
    private void searchTrainsMouseReleased(java.awt.event.MouseEvent evt) {
  		mainInstance.setVisible(false);
  		SearchTrain.searchTrainInstance.setLocationRelativeTo(null);
        SearchTrain.searchTrainInstance.setVisible(true);
  	}
    
    private void refreshMouseReleased(java.awt.event.MouseEvent evt) {
    	this.loginViewSet();
  	}
    
    private void viewTicketMouseReleased(java.awt.event.MouseEvent evt) {
    	int i = this.ticketsList.getSelectedIndex();
    	if (i != -1) { 
    		Main.mainInstance.client.sendThroughProtocol("clienViewTicketInfo", passenger.getTickets().get(i));
            Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
            String ans = message.getType();
            if (ans.equals("ok")) {
            	ScheduleDTO schedule = (ScheduleDTO) message.getObject();
            	JOptionPane.showMessageDialog(null, "Train number: " + schedule.getTrainNumber() + 
            			", departure station: "  + schedule.getStation1() + ", arrival station: "  
            			+ schedule.getStation2() + ", departure date: "  + schedule.getDateOfDeparture() +
            			", arrival date: "  + schedule.getDateOfArrival()); 
            } else if (ans.equals("no")) {
            	JOptionPane.showMessageDialog(null, "Sorry, but the operation was not successful, try to log out/log" +
            			" in and repeate the operation again!"); 
            }
    	} else {
    		JOptionPane.showMessageDialog(null, "Illegal selection, may be some updates happened, check ticket's list!"); 
    	}	
    }
    
    private void sellTicketsMouseReleased(java.awt.event.MouseEvent evt) {
    	int i = this.ticketsList.getSelectedIndex();
    	if (i != -1) { 
    		Main.mainInstance.client.sendThroughProtocol("clienSellTicket", passenger.getTickets().get(i));
            Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
            String ans = message.getType();
            if (ans.equals("ok")) {
            	JOptionPane.showMessageDialog(null, "You have successfully selled the ticket!"); 
            	Main.mainInstance.loginViewSet();
            } else if (ans.equals("no")) {
            	JOptionPane.showMessageDialog(null, "Sorry, but the operation was not successful!"); 
            }
    	} else {
    		JOptionPane.showMessageDialog(null, "Illegal selection, may be some updates happened, check ticket's list!"); 
    	}	
    }

    public static void main(String args[]) {
       
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            	try {
					Main.mainInstance.adress = InetAddress.getByName("localhost");
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
            	Main.mainInstance.client = new Client();
            	if (Main.mainInstance.client.startClient(mainInstance.adress, 1015)) {
            		Login.loginInstance.setLocationRelativeTo(null);
                    Login.loginInstance.setVisible(true);
            	}
            }
        });
    }
    
    private javax.swing.JButton viewTicket;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton logOut;
    private javax.swing.JButton sellTickets;
    private javax.swing.JList ticketsList;
    private JButton searchTrains;
}
